package cn.edu.njtc.controller;

import cn.edu.njtc.common.R;
import cn.edu.njtc.entity.pojo.Hospital;
import cn.edu.njtc.service.HospitalService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@Tag(name = "医院管理接口")
@RestController
@RequestMapping("/hospital")
public class HospitalController {

    @Autowired
    private HospitalService hospitalService;

    @Operation(summary = "新增医院")
    @PostMapping("/add")
    public R<String> addHospital(@RequestBody Hospital hospital) {
        if (!StringUtils.hasText(hospital.getHospitalName())) {
            return R.failed("医院名称不能为空");
        }
        // 检查医院名称是否已存在
        LambdaQueryWrapper<Hospital> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Hospital::getHospitalName, hospital.getHospitalName())
                .eq(Hospital::getDeleted, false); // 确保未删除的医院名称唯一
        if (hospitalService.count(queryWrapper) > 0) {
            return R.failed("医院名称已存在");
        }

        hospital.setCreated(LocalDateTime.now());
        hospital.setDeleted(false); // 默认未删除
        boolean success = hospitalService.save(hospital);
        if (success) {
            return R.ok("医院新增成功");
        }
        return R.failed("医院新增失败");
    }

    @Operation(summary = "更新医院信息")
    @PutMapping("/update")
    public R<String> updateHospital(@RequestBody Hospital hospital) {
        if (hospital.getHospitalId() == null) {
            return R.failed("医院ID不能为空");
        }
        // 如果更新了名称，需要检查新名称是否重复且不是当前医院本身
        if (StringUtils.hasText(hospital.getHospitalName())) {
            LambdaQueryWrapper<Hospital> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Hospital::getHospitalName, hospital.getHospitalName())
                    .eq(Hospital::getDeleted, false)
                    .ne(Hospital::getHospitalId, hospital.getHospitalId()); // 排除当前医院ID
            if (hospitalService.count(queryWrapper) > 0) {
                return R.failed("更新失败：医院名称已存在");
            }
        }

        hospital.setUpdated(LocalDateTime.now()); // 设置更新时间
        boolean success = hospitalService.updateById(hospital);
        if (success) {
            return R.ok("医院信息更新成功");
        }
        return R.failed("医院信息更新失败");
    }

    @Operation(summary = "根据ID查询医院详情")
    @GetMapping("/{id}")
    public R<Hospital> getHospitalById(@Parameter(description = "医院ID") @PathVariable Integer id) {
        Hospital hospital = hospitalService.getById(id);
        if (hospital != null && !hospital.getDeleted()) { // 确保医院存在且未被逻辑删除
            return R.ok(hospital);
        }
        return R.failed("未找到对应医院或已删除");
    }

    @Operation(summary = "分页查询医院列表")
    @GetMapping("/page")
    public R<Page<Hospital>> getHospitalPage(
            @Parameter(description = "页码，从1开始", example = "1") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "每页数量", example = "10") @RequestParam(defaultValue = "10") Integer pageSize,
            @Parameter(description = "医院名称关键词 (可选)", example = "北京") @RequestParam(required = false) String name) {

        Page<Hospital> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Hospital> queryWrapper = new LambdaQueryWrapper<>();

        if (StringUtils.hasText(name)) {
            queryWrapper.like(Hospital::getHospitalName, name);
        }
        queryWrapper.eq(Hospital::getDeleted, false); // 仅查询未被逻辑删除的医院
        queryWrapper.orderByDesc(Hospital::getCreated); // 按创建时间倒序

        Page<Hospital> hospitalPage = hospitalService.page(page, queryWrapper);
        return R.ok(hospitalPage);
    }

    @Operation(summary = "获取所有医院列表")
    @GetMapping("/list")
    public R<List<Hospital>> getAllHospitals() {
        LambdaQueryWrapper<Hospital> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Hospital::getDeleted, false); // 仅查询未被逻辑删除的医院
        List<Hospital> hospitals = hospitalService.list(queryWrapper);
        return R.ok(hospitals);
    }

    @Operation(summary = "逻辑删除医院")
    @DeleteMapping("/delete/{id}")
    public R<String> deleteHospital(@Parameter(description = "医院ID") @PathVariable Integer id) {
        Hospital hospital = hospitalService.getById(id);
        if (hospital == null || hospital.getDeleted()) {
            return R.failed("医院不存在或已删除");
        }
        hospital.setDeleted(true); // 设置为逻辑删除
        hospital.setUpdated(LocalDateTime.now());
        boolean success = hospitalService.updateById(hospital); // 使用updateById进行逻辑删除
        if (success) {
            return R.ok("医院删除成功");
        }
        return R.failed("医院删除失败");
    }

    // 批量逻辑删除
    @Operation(summary = "批量逻辑删除医院")
    @DeleteMapping("/batchDelete")
    public R<String> batchDeleteHospitals(@Parameter(description = "医院ID列表") @RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return R.failed("删除ID列表不能为空");
        }
        // 批量更新 deleted 字段
        List<Hospital> hospitalsToUpdate = ids.stream()
                .map(id -> {
                    Hospital hospital = new Hospital();
                    hospital.setHospitalId(id);
                    hospital.setDeleted(true);
                    hospital.setUpdated(LocalDateTime.now());
                    return hospital;
                })
                .toList();

        boolean success = hospitalService.updateBatchById(hospitalsToUpdate);
        if (success) {
            return R.ok("批量删除医院成功");
        }
        return R.failed("批量删除医院失败");
    }
}